package com.ityxh.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ityxh.common.returns.R;
import com.ityxh.common.annotation.Idempotent;
import com.ityxh.entity.Driver;
import com.ityxh.service.DriverService;
import com.ityxh.utils.RedisUtil;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.security.auth.message.AuthException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

@RestController
@RequestMapping("/driver")
@Slf4j
@AllArgsConstructor
public class DriverController {

    private final DriverService driverService;

    private final RedisUtil redisUtil;

    @GetMapping("/test")
    public R testDriver() {
        return R.ok("测试司机！");
    }


    @SneakyThrows
    @GetMapping("/driverPage")
    @Idempotent(key = "'driver_'", expireTime = 10, info = "请求过于频繁_请稍后重试")
    public R getDriverPage(Page<Driver> page, Driver driver) {
        LambdaQueryWrapper<Driver> query = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(driver.getRealName())) {
            query.like(Driver::getRealName, driver.getRealName());
            driver.setRealName(null);
        }
        log.error(Thread.currentThread().getName());
        query.orderByDesc(Driver::getCreateTime);
        return R.ok(driverService.page(page, query));
    }

    /**
     * 图形验证码id,无值：生成验证码，有值:刷新验证码
     *
     * @return
     */
    @Idempotent(key = " 'identifyImage_' + #codeId", expireTime = 10, info = "请求过于频繁_请稍后重试")
    @GetMapping("/identifyImage")
    public R<String> identifyImage(HttpServletResponse response,
                                   //required = false  如果不传默认Null
                                   @RequestParam(name = "codeId", required = false) String codeId) throws Exception {

        // 创建验证码，设置宽、高、长度、干扰线数量
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 90, 4, 100);
        // 获取验证码字符串，赋值code
        String code = lineCaptcha.getCode();

        if (codeId == null) {
            // IdWorker.getId():IdWorker工具类生成唯一ID,并转换成String类型
            codeId = String.valueOf(IdWorker.getId());
            // 将codeId、code.toUpperCase()、过期时间60秒：存储入Redis中
            // code.toUpperCase():code装换成大写形式存储
            redisUtil.set(codeId, code.toUpperCase(), 60);
        } else {
            redisUtil.set(codeId, code.toUpperCase(), 60);
        }

        // 将图片验证码codeId设置请求头中
        response.setHeader("codeId", codeId);
        // 获取向客户端发送响应数据的输出流
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            // 验证码图片数据写入到输出流
            lineCaptcha.write(outputStream);
        } catch (Exception e) {
            throw new AuthException("图形验证码输出错误");
        }
        return R.ok(codeId);
    }


    /**
     * 生成验证码图片
     *
     * @return
     */
    @GetMapping("/identifyImages")
    public R identifyImages(HttpServletResponse response,
                            @RequestParam(name = "codeId", required = false) String codeId) throws Exception {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 90, 4, 100);
        String code = lineCaptcha.getCode();
        if (codeId == null) {
            codeId = String.valueOf(IdWorker.getId());
            redisUtil.set(codeId, code.toUpperCase(), 60);
        } else {
            redisUtil.set(codeId, code.toUpperCase(), 60);
        }
        // Encode byte array to Base64
        return R.ok(lineCaptcha);
    }


}
